#include <iostream>
using namespace std;
#include <unistd.h>
#include <pthread.h>
#include <vector>
#include <cstdio>
// 下面的代码逻辑是写出五个线程实现抢票逻辑
// 一共1000张票 如果票数大于0就开始抢票tik--
// 如果票数小于0就直接退出 
const int NUM = 5;
int ticket = 1000;
pthread_mutex_t mutex;
void* get_ticket(void* args)
{
  while(1)
  {
      pthread_mutex_lock(&mutex);
    if(ticket > 1)
    {
      usleep(10000);
      printf("i get a ticket im:%x , ticket left:%d\n", pthread_self() , --ticket);
      pthread_mutex_unlock(&mutex);
    }
    else 
    {
      pthread_mutex_unlock(&mutex);
      break;
    }
  }
  pthread_exit((void*)0);
}

int main()
{
  pthread_t tid;
  vector<pthread_t> v;
  pthread_mutex_init(&mutex , NULL);
  int i = 0;
  for (i = 0; i < NUM ; i++)
  {
    pthread_create(&tid , NULL , get_ticket , (void *)"new pthread");
    v.push_back(tid);
  }

  for (i = 0; i < NUM ; i++)
  {
    pthread_join(v[i] , NULL);
  }
  pthread_mutex_destroy(&mutex);
  return 0;
}
